#!/usr/bin/env python

import sys
import kalcompile
import kal_parse

def main():
    if len(sys.argv) < 2:
        print 'usage: kal.py [-r] file'
    if sys.argv[1] == '-r':
        kalcompile.parse_grammar()
        reload(kal_parse)
        file_name = sys.argv[2]
        if len(sys.argv) == 4:
            base_class = sys.argv[3]
        else:
            base_class = 'KalFile'
    else:
        file_name = sys.argv[1]
        if len(sys.argv) == 3:
            base_class = sys.argv[2]
        else:
            base_class = 'KalFile'
    with open(file_name,'r') as f:
        code = f.read()
    try:
        kal_parse.parse(code,kal_parse.__dict__[base_class]).print_tree(0,'root')
        sys.stdout.write('\n')
    except kal_parse.KalASTParseError, e:
        print str(e)
    return 0


if __name__ == '__main__':
    sys.exit(main())